#include <iostream>
#include <pthread.h>
#include <unistd.h>

using namespace std;

class Singleton{
private:
    static Singleton *gInstance;
    static pthread_mutex_t g_tMutex;

    Singleton() {
        cout << "Singleton()..." << endl;
    };
public:
    static Singleton* getInstance() {
//        if (NULL == gInstance) {
//            pthread_mutex_lock(&g_tMutex);
//            if (NULL == gInstance) {
//                gInstance = new Singleton();
//            }
//            pthread_mutex_unlock(&g_tMutex);
//        }
        return gInstance;
    }

//    Singleton() {
//        cout << "Singleton()..." << endl;
//    };

    void printfInfo() {
        cout << "printfInfo()..." << endl;
    }
};

Singleton *Singleton::gInstance = new Singleton;
//pthread_mutex_t Singleton::g_tMutex = PTHREAD_MUTEX_INITIALIZER;

void *start_routine_thread1(void *arg) {
    cout << "This is thread 1" << endl;
    Singleton *s = Singleton::getInstance();
    s->printfInfo();

    return NULL;
}

void *start_routine_thread2(void *arg) {
    cout << "This is thread 2" << endl;
    Singleton *s = Singleton::getInstance();
    s->printfInfo();

    return NULL;
}

int main() {
    Singleton *s = Singleton::getInstance();
    s->printfInfo();
//
//    Singleton *s1 = Singleton::getInstance();
//    s1->printfInfo();

//    Singleton s2 = new Singleton();

    pthread_t threadId1;
    pthread_t threadId2;

    pthread_create(&threadId1, NULL, start_routine_thread1, NULL);
    pthread_create(&threadId2, NULL, start_routine_thread2, NULL);

    sleep(3);

    return 0;
}
